package com.yk.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yk.api.system.dto.ConfigurationDTO;
import com.yk.system.convert.ConfigurationConvert;
import com.yk.system.entity.Configuration;
import com.yk.system.entity.GroupConfiguration;
import com.yk.system.mapper.ConfigurationMapper;
import com.yk.system.mapper.GroupConfigurationMapper;
import com.yk.system.service.ConfigurationService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author lmx
 * @date 2023/10/24 9:44
 */
@Service
@RequiredArgsConstructor
public class ConfigurationServiceImpl extends ServiceImpl<ConfigurationMapper, Configuration> implements ConfigurationService {

    private final GroupConfigurationMapper groupConfigurationMapper;
    private final ConfigurationConvert configurationConvert;

    @Override
    public int updateBatch(List<Configuration> list) {
        return baseMapper.updateBatch(list);
    }

    @Override
    public int batchInsert(List<Configuration> list) {
        return baseMapper.batchInsert(list);
    }

    @Override
    public List<ConfigurationDTO> getConfigurationDTOS(Long groupId, String name) {
        LambdaQueryWrapper<GroupConfiguration> lambda = new LambdaQueryWrapper<>();
        lambda.eq(GroupConfiguration::getGroupId, groupId);
        List<GroupConfiguration> list = groupConfigurationMapper.selectList(lambda);
        List<ConfigurationDTO> dtoList = CollUtil.newArrayList();
        if (CollUtil.isNotEmpty(list)) {
            List<Long> ids = list.stream().map(GroupConfiguration::getConfigurationId).collect(Collectors.toList());
            LambdaQueryWrapper<Configuration> wrapper = new LambdaQueryWrapper<>();
            wrapper.like(StrUtil.isNotEmpty(name), Configuration::getName, name);
            wrapper.in(Configuration::getId, ids);
            List<Configuration> configurations = baseMapper.selectList(wrapper);
            dtoList = Optional.ofNullable(configurations).orElse(CollUtil.newArrayList())
                    .stream()
                    .map(configurationConvert::entity2Dto)
                    .collect(Collectors.toList());
        }
        return dtoList;
    }
}
